<?php
// 应用公共文件

// 应用公共文件
// 应用公共文件
//use app\api\model\SmsLog;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use think\facade\Db;

function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

    return $msectime;
}

function GetUserId($token)
{
    $user_id = Db::name('users')->where(array('token' => $token))->value('user_id');
    if (empty($user_id)) {
        $data = array(
            'code' => '4001',
            'msg' => '用户不存在'
        );
        exit(json_encode($data));
    }
    return $user_id;
}

/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile)
{
    if (preg_match('/1[345789]\d{9}$/', $mobile))
        return true;
    return false;
}

// 自动生成随机用户名
// 测试，循环创建1万个随机账号，0碰撞，10万大约0-3个碰撞，足够应付未来数十亿级PV
function genUserNumber()
{
    $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $username = "";
    for ($i = 0; $i < 6; $i++) {
        $username .= $chars[mt_rand(0, strlen($chars))];
    }
    return strtoupper(base_convert(time() - 1420070400, 10, 36)) . $username;
}

function getTree($array, $pid = 0)
{
    static $data = array();
    foreach ($array as $key => $val) {
        if ($val['parent_id'] == $pid) {
            $data[] = $val;
            unset($array[$key]);
            getTree($array, $val['id']);// 进行递归
        }
    }
    return $data;
}

// 实现多维数组形式
function getTree2($array)
{
    $refer = array();
    $tree = array();
    foreach ($array as $key => $val) {
        $array[$key]['child'] = [];
        $refer[$val['id']] = &$array[$key];

    }

    foreach ($array as $k => $v) {
        $pid = $v['parent_id']; //获取当前分类的父级id
        if ($pid == 0) {
            $tree[] = &$array[$k]; //顶级栏目
        } else {
            if (isset($refer[$pid])) {
                $refer[$pid]['child'][] = &$array[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
            }
        }
    }

    return $tree;
}

function getTreeCommon($array,$parent_id='category_id',$child_id='cate_id'): array
{
    $refer = array();
    $tree = array();
    foreach ($array as $key => $val) {
        $array[$key]['child'] = [];
        $refer[$child_id] = &$array[$key];

    }

    foreach ($array as $k => $v) {
        $pid = $v[$parent_id]; //获取当前分类的父级id
        if ($pid == 0) {
            $tree[] = &$array[$k]; //顶级栏目
        } else {
            if (isset($refer[$pid])) {
                $refer[$pid]['child'][] = &$array[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
            }
        }
    }

    return $tree;
}

/**
 * 邮件发送
 * @param $to    接收人
 * @param string $subject 邮件标题
 * @param string $content 邮件内容(html模板渲染后的内容)
 * @throws Exception
 * @throws phpmailerException
 */
function send_Email($to, $subject = '', $content = '')
{


    //判断openssl是否开启
    $openssl_funcs = get_extension_funcs('openssl');
    if (!$openssl_funcs) {
        return array('status' => -1, 'msg' => '请先开启openssl扩展');
    }
    $mail = new PHPMailer;
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;
    //调试输出格式
    //$mail->Debugoutput = 'html';
    //smtp服务器
    $mail->Host = 'smtp.qq.com';
    //端口 - likely to be 25, 465 or 587
    $mail->Port = 465;

    if ($mail->Port == 465) $mail->SMTPSecure = 'ssl';// 使用安全协议
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //用户名
    $mail->Username = 'awnagxiaogang@qq.com';
    //密码
    $mail->Password = 'mgrdlaekybcybidc';
    //Set who the message is to be sent from
    $mail->setFrom('awnagxiaogang@qq.com');
    //回复地址
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //接收邮件方
    if (is_array($to)) {
        foreach ($to as $v) {
            $mail->addAddress($v);
        }
    } else {
        $mail->addAddress($to);
    }

    $mail->isHTML(true);// send as HTML
    //标题
    $mail->Subject = $subject;
    //HTML内容转换
    $mail->msgHTML($content);
    //Replace the plain text body with one created manually
    //$mail->AltBody = 'This is a plain-text message body';
    //添加附件
    //$mail->addAttachment('images/phpmailer_mini.png');
    //send the message, check for errors
    if (!$mail->send()) {
        return array('code' => -1, 'msg' => '发送失败: ' . $mail->ErrorInfo);
    } else {
        return array('code' => 1, 'msg' => '发送成功');
    }
}


function isEmail($email)
{
    return preg_match("/^([a-z0-9]*[-_＼.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[＼.][a-z]{2,4}([＼.][a-z]{2})?$/i", $email);
}


/**
 * @param array $dataArr 需要分组的数据
 * @param string $keyStr 分组依据
 * @return array
 */
function dataGroupChild(array $dataArr, string $keyStr)
{

    $data = [];
    $newArr = [];
    foreach ($dataArr as $k => $val) {
        if ($val[$keyStr] > 0) {
            $newArr[$val[$keyStr]][] = $val;
        } else {
            $data[$k] = $val;
        }
    }
    $list = [];
    foreach ($newArr as $key => $item) {
        $price = 0;
        $download = 0;
        $list[$key]['model_type'] = 2;
        $list[$key]['id'] = $key;
        $list[$key]['title'] = $item[0]['getGoodsGroup']['group_name'];
        $list[$key]['thumb'] = json_decode($item[0]['getGoodsGroup']['thumb'], true);
        $list[$key]['status'] = $item[0]['getGoodsGroup']['status'];
        $list[$key]['collect'] = 0;
        $list[$key]['browse'] = 1;
        $list[$key]['create_time'] = $item[0]['getGoodsGroup']['create_time'];
        foreach ($item as $k => $v) {
            $price += $v['file_price'];
            $download += $v['download'];
            $item[$k]['file_format'] = $v['file_format'] ? explode(',', $v['file_format']) : "";
            $item[$k]['tag'] = $v['tag'] ? explode(',', $v['tag']) : "";
            $item[$k]['status_type'] = $v['status_type'] ? explode(',', $v['status_type']) : "";
        }
        $list[$key]['download'] = $download;
        $list[$key]['file_price'] = $price;
        $list[$key]['sale_mode'] = 0;
        $list[$key]['children'] = $item;
    }
    $arr = [];
    foreach ($data as $k => $vv) {
        $arr[$k] = $vv;
        $arr[$k]['file_format'] = $vv['file_format'] ? explode(',', $vv['file_format']) : "";
        $arr[$k]['tag'] = $vv['tag'] ? explode(',', $vv['tag']) : "";
        $arr[$k]['status_type'] = $vv['status_type'] ? explode(',', $vv['status_type']) : "";
        $arr[$k]['collect'] = 0;
        $arr[$k]['browse'] = 1;


        $arr[$k]['children'] = [];
    }

    return array_merge($list, $arr);

}

/***
 * @param array $dataArr
 * @param string $keyStr
 * @return array
 */
function PublicDataGroup(array $dataArr, string $keyStr)
{

    $data = [];
    $newArr = [];
    foreach ($dataArr as $k => $val) {
        if ($val[$keyStr] > 0) {
            $newArr[$val[$keyStr]][] = $val;
        } else {
            $data[$k] = $val;
        }

    }

    $arr = [];
    foreach ($newArr as $key => $item) {
        foreach ($item as $kk => $vv) {
            if ($key == $vv['group_id']) {
                $arr[$key] = $vv;
            }
        }
    }


    return array_merge($data, $arr);
}

/***
 * @param $data
 * @param $keyword
 * @return array
 */
function arraySearch($data, $cate_id)
{

    $arr = [];
    foreach ($data as $key => $item) {


        foreach ($item['cate_id'] as $kk => $vv) {
            if ($vv['parent_id'] == $cate_id || $vv['cateid'] == $cate_id) {
                $arr[$key] = $item;
            }

        }
    }
    return $arr;
}

/**
 * @param array $dataArr 需要分组的数据
 * @param string $keyStr 分组依据
 * @return array
 */
function dataGroup(array $dataArr, string $keyStr)
{

    $data = [];
    $newArr = [];
    foreach ($dataArr as $k => $val) {
        if ($val['file_price'] > 0 && $val['sale_mode'] == 1) {
            $val['file_price'] = number_format($val['file_price'] / 10, 2);
        }
        if ($val[$keyStr] > 0) {
            $newArr[$val[$keyStr]][] = $val;
        } else {
            $data[$k] = $val;
        }

    }


//    print_r($newArr);die;

    $arr = [];
    $find = [];
    foreach ($newArr as $key => $item) {
        foreach ($item as $kk => $vv) {
            if ($key == $vv['group_id']) {
                $arr[$key] = $vv;
                if ($vv['cate_id'] == 186) {
                    $find[$key] = $vv;
                }

            }
        }
    }

    foreach ($arr as $key => $item) {
        foreach ($find as $k => $v) {
            if ($key == $k) {
                $arr[$key] = $v;
            }
        }
    }

    return array_merge($data, $arr);
}


/**
 * @param array $dataArr 需要分组的数据
 * @param string $keyStr 分组依据
 * @return array
 */
function OrderGroup(array $dataArr, string $keyStr)
{

    $data = [];
    $newArr = [];
    foreach ($dataArr as $k => $val) {
        if ($val[$keyStr] > 0) {
            $newArr[$val[$keyStr]][] = $val;
        } else {
            $data[$k] = $val;
        }

    }
    $list = [];
    foreach ($newArr as $key => $item) {
        $list[$key] = $item[0];
        unset($item[0]);
        $list[$key]['children'] = count($item) > 0 ? $item : [];
    }

    return array_merge($list);
}

/*
@desc：获取图片真实后缀
@param   name    文件名
@return  suffix  文件后缀
*/
function getimgsuffix($name)
{
    $info = getimagesize($name);

    $suffix = false;
    if ($mime = $info['mime']) {
        $suffix = explode('/', $mime)[1];
    }
    return $suffix;
}

/***
 * @inheritDoc 获取文件地址
 * @param $filename
 * @return mixed|string|null
 */
function getExt1($filename)

{
    $arr = explode('.', $filename);
    return array_pop($arr);

}


function is_url($url): int
{
    if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
        return 1;
    } else {
        return 0;
    }
}

function geturlpic($file_url, $save_to)
{
    $content = file_get_contents($file_url);
    file_put_contents($save_to, $content);

}

function mkFolder($path)

{
    if (!is_readable($path)) {
        is_file($path) or mkdir($path, 0700);

    }

}

function sendCheck($mobile, $code)
{
    $timeOut = time();
    $inValid = true;  //验证码失效
    //短信
    $sms_time_out = ''; //设置验证码有效期
    $sms_time_out = $sms_time_out ? $sms_time_out : 3000;
    $data = SmsLog::where(array('phone' => $mobile, 'status' => 1))->order('id DESC')->find();


    !empty($data) ? $data = $data->toArray() : $data = [];

    if (is_array($data) && $data['code'] == $code) {
        $data['sender'] = $mobile;
        $timeOut = $data['create_time'] + $sms_time_out;
    } else {
        $inValid = false;
    }
    if (empty($data)) {
        $res = array('code' => -1, 'msg' => '请先获取验证码');
        return $res;
    } elseif ($timeOut < time()) {
        $res = array('code' => -1, 'msg' => '验证码已超时失效');
        return $res;

    } elseif (!$inValid) {
        $res = array('code' => -1, 'msg' => '验证失败,验证码有误');
        return $res;
    } elseif ($data['is_check'] == 1) {
        $res = array('code' => -1, 'msg' => '验证码已经用过啦');
        return $res;
    } else {

        session('validate_code', $data);
        $res = array('code' => 1, 'msg' => '验证成功');
        return $res;
    }
}

function ToXml($data)
{
    if (!is_array($data) || count($data) <= 0) {
        throw new \WxPayException("数组数据异常！");
    }

    $xml = "<xml>";
    foreach ($data as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}

/***
 * @param $cate_id
 * @return string
 */
function CateJson($cate_id)
{
    $arr = [];
    foreach ($cate_id as $kk => $vv) {
        if (!empty($vv['parent_id'])) {
            $arr[] = $vv['parent_id'];
            foreach ($vv['cateid'] as $kkk => $vvv) {
                $arr[] = $vvv['cate_id'];
            }
        }

    }
    !empty($arr) ? $ids = implode(',', $arr) : $ids = [];

    return $ids;
}
